package com.loong.musicdemo.ui.cloudtown.videos;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.loong.musicdemo.R;
import com.loong.musicdemo.model.SongList;
import com.loong.musicdemo.adapter.PlayListAdapter;
import com.loong.musicdemo.util.dataDeal.PlayListDeal;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 通过传入视频分类id以及分类名称创建一个新的fragment
 */
public class VideoPager extends Fragment {
    private static final String VIDEO_GROUP_NAME = "NAME";
    private String name;
    private SmartRefreshLayout loading;//上啦加载
    private SwipeRefreshLayout refresh;//下拉刷新
    private RecyclerView recyclerVideo;//视频列表
    private final List<SongList> songLists = new ArrayList<>();//歌单列表
    private LinearLayout tips;
    private PlayListAdapter adapter;
    private ProgressBar progressBar;
    private int page = 0;

    public VideoPager() {
    }

    public static Fragment newInstance(String name) {
        VideoPager fragment = new VideoPager();
        Bundle args = new Bundle();
        args.putString(VIDEO_GROUP_NAME, name);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            name = getArguments().getString(VIDEO_GROUP_NAME);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden)
            Glide.with(this).onLowMemory();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_video_pager, container, false);
        initView(root);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        recyclerVideo.setLayoutManager(layoutManager);
        adapter = new PlayListAdapter(songLists);
        recyclerVideo.setAdapter(adapter);
        new GetPlayListByTag().execute();
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Glide.with(this).onLowMemory();
    }

    /**
     * 初始话布局以及事件
     *
     * @param root 根视图
     */
    private void initView(View root) {
        //下拉刷新
        refresh = root.findViewById(R.id.refresh_videos);
        refresh.setColorSchemeResources(R.color.neteaseRed);
        refresh.setOnRefreshListener(() -> {
            new GetPlayListByTag().execute();
        });
        //上啦加载
        loading = root.findViewById(R.id.loading);
        loading.setEnableRefresh(false);//禁用下拉
        loading.autoLoadmore();//加载更多
        loading.setOnLoadmoreListener(refreshlayout -> {
            new LoadPlayListByGroup().execute();//加载后续数据
        });
        recyclerVideo = root.findViewById(R.id.recycler_videos);
        tips = root.findViewById(R.id.tips);
        progressBar = root.findViewById(R.id.progress_bar);
    }

    /**
     * 获取视频信息,用于刷新以及初始化
     */
    @SuppressLint("StaticFieldLeak")
    class GetPlayListByTag extends AsyncTask<Void, Void, List<SongList>> {

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected List<SongList> doInBackground(Void... voids) {
            page = 0;
            return PlayListDeal.getPlayListByTag(name, page++);
        }

        @Override
        protected void onPostExecute(List<SongList> longListPair) {
            super.onPostExecute(longListPair);
            if (longListPair == null || longListPair.size() == 0) {//数据获取失败
                if (songLists.size() == 0) {
                    tips.setVisibility(View.VISIBLE);
                    refresh.setVisibility(View.GONE);
                } else {//如果第二次 获取不到数据,则直接使用旧数据
                    if (refresh.isRefreshing()) {
                        refresh.setRefreshing(false);
                        Toast.makeText(requireContext(), "您的歌单已是最新,无需刷新", Toast.LENGTH_SHORT).show();
                    }
                    tips.setVisibility(View.GONE);
                    refresh.setVisibility(View.VISIBLE);
                }
            } else {
                if (refresh.isRefreshing()) {
                    refresh.setRefreshing(false);
                    Toast.makeText(requireContext(), "歌单已刷新", Toast.LENGTH_SHORT).show();
                }
                if (isAdded()) {//判断当前是否已加载到Activity
                    songLists.addAll(longListPair);
                    adapter.notifyDataSetChanged();
                    tips.setVisibility(View.GONE);
                    refresh.setVisibility(View.VISIBLE);
                }
            }
            progressBar.setVisibility(View.GONE);
        }
    }

    /**
     * 获取视频信息,用于下拉加载
     */
    @SuppressLint("StaticFieldLeak")
    class LoadPlayListByGroup extends AsyncTask<Void, Void, List<SongList>> {

        @Override
        protected List<SongList> doInBackground(Void... voids) {
            return PlayListDeal.getPlayListByTag(name, page++);
        }

        @Override
        protected void onPostExecute(List<SongList> listPair) {
            super.onPostExecute(listPair);
            if (listPair == null || listPair.size() == 0) {
                loading.finishLoadmore();
                Toast.makeText(requireContext(), "没有更多精品歌单适合您了", Toast.LENGTH_SHORT).show();
            } else {
                songLists.addAll(listPair);
                adapter.notifyDataSetChanged();
                Toast.makeText(requireContext(), "加载成功", Toast.LENGTH_SHORT).show();
                loading.finishLoadmore();
            }
        }
    }
}
